package io.bhex.app.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.baselib.core.CApplication;
import io.bhex.baselib.utils.ToastUtils;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2020-04-02
 * 邮   箱：
 * 描   述：
 * ================================================
 */

public class BHTabView extends HorizontalScrollView {
    private LinearLayout tabLayout;
    private int textColor;
    private float textSize;
    private int selectTextColor;
    private float selectTextSize;
    private int unselectTextColor;
    private float unselectTextSize;
    private int defaultSelectPosition;
    private int selectTextAppearance;
    private int unselectTextAppearance;
    private float marginStart;
    private float marginEnd;
    private float marginTop;
    private float marginBottom;
    private List<TextView> tabViews = new ArrayList<>();
    private View indicatorView;
    private boolean showIndicator;
    private int indicatorColor;
    private float indicatorWidth;
    private float indicatorHeight;
    private float indicatorMarginTop;
    private float paddingStart;
    private float paddingEnd;
    private float paddingTop;
    private float paddingBottom;
    private int selectTextAppearanceNight;
    private int unselectTextAppearanceNight;
    private boolean isNightSkin=false;

    public BHTabView(Context context) {
        super(context,null);
    }

    public BHTabView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
        initAttrs(context,attrs);
    }

    public BHTabView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        initAttrs(context,attrs);
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BHTabView);
//        int bgColor = typedArray.getColor(R.styleable.BHTabView_bgColor, -1);
//        if (bgColor!=-1) {
//            tabRootView.setBackgroundColor(bgColor);
//        }

            textColor = typedArray.getColor(R.styleable.BHTabView_textColor, -1);
            textSize = typedArray.getDimension(R.styleable.BHTabView_textSize, 14);
            selectTextColor = typedArray.getColor(R.styleable.BHTabView_selectTextColor, -1);
            selectTextSize = typedArray.getDimension(R.styleable.BHTabView_selectTextSize, 20);
            selectTextAppearance = typedArray.getResourceId(R.styleable.BHTabView_selectTextAppearance,-1);
            selectTextAppearanceNight = typedArray.getResourceId(R.styleable.BHTabView_selectTextAppearanceNight,-1);
            unselectTextColor = typedArray.getColor(R.styleable.BHTabView_unselectTextColor, -1);
            unselectTextSize = typedArray.getDimension(R.styleable.BHTabView_unselectTextSize, 14);
            unselectTextAppearance = typedArray.getResourceId(R.styleable.BHTabView_unselectTextAppearance,-1);
            unselectTextAppearanceNight = typedArray.getResourceId(R.styleable.BHTabView_unselectTextAppearanceNight,-1);
            marginStart = typedArray.getDimension(R.styleable.BHTabView_marginStart, dp2px(8));//默认8dp
            marginEnd = typedArray.getDimension(R.styleable.BHTabView_marginEnd, dp2px(8));//默认8dp
            marginTop = typedArray.getDimension(R.styleable.BHTabView_marginTop, dp2px(4));//默认8dp
            marginBottom = typedArray.getDimension(R.styleable.BHTabView_marginBottom, dp2px(4));//默认8dp
            paddingStart = typedArray.getDimension(R.styleable.BHTabView_paddingStart, dp2px(8));//默认8dp
            paddingEnd = typedArray.getDimension(R.styleable.BHTabView_paddingEnd, dp2px(8));//默认8dp
            paddingTop = typedArray.getDimension(R.styleable.BHTabView_paddingTop, dp2px(8));//默认8dp
            paddingBottom = typedArray.getDimension(R.styleable.BHTabView_paddingBottom, dp2px(6));//默认8dp
            defaultSelectPosition = typedArray.getInteger(R.styleable.BHTabView_defaultSelectPosition, 0);

           //指示器配置
            showIndicator = typedArray.getBoolean(R.styleable.BHTabView_showIndicator, true);//默认显示
            indicatorColor = typedArray.getColor(R.styleable.BHTabView_indicatorColor, -1);//默认显示
            indicatorWidth = typedArray.getDimension(R.styleable.BHTabView_indicatorWidth, -1);
            indicatorHeight = typedArray.getDimension(R.styleable.BHTabView_indicatorHeight, dp2px(2));
            indicatorMarginTop = typedArray.getDimension(R.styleable.BHTabView_indicatorMarginTop, dp2px(2));
            typedArray.recycle();
        }
    }

    private void initView(Context context) {
        View tabRootView = LayoutInflater.from(context).inflate(R.layout.bh_table_layout, this, true);
        tabLayout = tabRootView.findViewById(R.id.tabLayout);
        indicatorView = tabRootView.findViewById(R.id.indicator);
        indicatorView.setVisibility(showIndicator ? VISIBLE : GONE);
        this.setHorizontalScrollBarEnabled(false);
    }

    /**
     * 设置tabs和点击切换事件监听
     * @param tabTitles
     * @param tabListener
     */
    public void setTabs(List<String> tabTitles,OnTabListener tabListener){
        tabViews.clear();
        tabLayout.removeAllViews();
        if (tabTitles != null && tabTitles.size()>0) {
            for (int i = 0; i < tabTitles.size(); i++) {
                String tabTitle = tabTitles.get(i);
                TextView tabView = new TextView(getContext());
                tabView.setTag(i);
                tabView.setText(tabTitle);
                //设置点击事件
                tabView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int selectPostion = (Integer) v.getTag();
                        defaultSelectPosition = selectPostion;
                        tabListener.onSelect(selectPostion);
                        updateTabsStyle(tabViews,selectPostion);
                    }
                });

                if (i == defaultSelectPosition) {
                    setTabStyle(tabView,true);
                }else{
                    setTabStyle(tabView,false);
                }

                tabViews.add(tabView);
                tabLayout.addView(tabView);
            }

            //首次主动触发默认tab的点击事件
            activeTriggerDefaultTabClick();
        }
    }

    /**
     * 首次主动触发默认tab的点击事件
     */
    private void activeTriggerDefaultTabClick() {
        if (tabViews != null && tabViews.size()>0) {
           if(defaultSelectPosition < tabViews.size()){
               TextView defaultTabView = tabViews.get(defaultSelectPosition);
               defaultTabView.performClick();
           }


        }
    }

    public void switchSkin(boolean isNight){
        isNightSkin = isNight;
        updateTabsStyle(tabViews,defaultSelectPosition);
    }

    /**
     * 更新style样式
     * @param tabViews
     * @param selectPostion
     */
    private void updateTabsStyle(List<TextView> tabViews,int selectPostion) {
        for (int i = 0; i < tabViews.size(); i++) {
            TextView tabView = tabViews.get(i);
            setTabStyle(tabView,i == selectPostion);
        }
    }

    /**
     * 设置tab样式
     * @param tabView
     * @param isSelect
     */
    private void setTabStyle(TextView tabView, boolean isSelect) {
        tabView.setTextSize(TypedValue.COMPLEX_UNIT_SP,textSize);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = (int) marginStart;
        layoutParams.topMargin = (int) marginTop;
        layoutParams.rightMargin = (int) marginEnd;
        layoutParams.bottomMargin = (int) marginBottom;
        tabView.setLayoutParams(layoutParams);
        tabView.setPadding((int)paddingStart,(int)paddingTop,(int)paddingEnd,(int)paddingBottom);
        if (textColor!=-1) {
            tabView.setTextColor(textColor);
        }
        if (isSelect) {
            //选中tab状态
            if (selectTextColor!=-1) {
                tabView.setTextColor(selectTextColor);
            }
            tabView.setTextSize(TypedValue.COMPLEX_UNIT_SP,selectTextSize);
            if (selectTextAppearance!=-1) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    tabView.setTextAppearance(isNightSkin ? selectTextAppearanceNight : selectTextAppearance);
                }
            }
            this.smoothScrollTo((int)(tabView.getX() - this.getWidth()/2),0);

            setIndicatorStyle(tabView);

        }else{
            //未选中tab状态
            if (unselectTextColor!=-1) {
                tabView.setTextColor(unselectTextColor);
            }
            tabView.setTextSize(TypedValue.COMPLEX_UNIT_SP,unselectTextSize);
            if (unselectTextAppearance!=-1) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    tabView.setTextAppearance(isNightSkin ? unselectTextAppearanceNight : unselectTextAppearance);
                }
            }
        }
    }

    /**
     * 设置指示器样式
     * @param tabView
     */
    private void setIndicatorStyle(TextView tabView) {
        if (!showIndicator) {
            return;
        }
        indicatorView.setVisibility(VISIBLE);

        tabView.measure(0,0);
        int measuredTabWidth = tabView.getMeasuredWidth();

        LinearLayout.LayoutParams indicatorViewLayoutParams = (LinearLayout.LayoutParams) indicatorView.getLayoutParams();
        boolean isSetIndicatorWidth = indicatorWidth != -1;
        if (isSetIndicatorWidth) {
            //设置了固定宽度
            indicatorViewLayoutParams.width = (int) indicatorWidth;
        }else{
            //没有设置固定宽度-就默认跟随tab title的文案宽度
            indicatorViewLayoutParams.width = measuredTabWidth - (int)paddingStart - (int)paddingEnd;
        }

        indicatorViewLayoutParams.height = (int) indicatorHeight;
        int tabPosition = (int) tabView.getTag();
        if (tabPosition==0) {
            indicatorViewLayoutParams.leftMargin = (int)marginStart + (int)paddingStart;
        }else{
            indicatorViewLayoutParams.leftMargin = 0 + (int)paddingStart;
        }
        indicatorViewLayoutParams.topMargin = (int) indicatorMarginTop;

        indicatorView.setLayoutParams(indicatorViewLayoutParams);
        if (indicatorColor!=-1) {
            indicatorView.setBackgroundColor(indicatorColor);
        }
        float scrollX;
        if (isSetIndicatorWidth) {
            if (tabPosition == 0) {
                scrollX = 0 + measuredTabWidth/2 - indicatorWidth/2 - paddingStart;
            }else{
                scrollX = tabView.getLeft()  + measuredTabWidth/2 - indicatorWidth/2 -paddingStart;
            }
        }else{
            if (tabPosition == 0) {
                scrollX = 0;
            }else{
                scrollX = tabView.getLeft();
            }
        }
        AnimalUtils.transAnimRun(indicatorView, indicatorView.getX(),  scrollX);
    }

    public interface OnTabListener{
        void onSelect(int position);
    }


    public static int dp2px(float value) {
        final float scale = CApplication.getInstance().getResources().getDisplayMetrics().density;
        return (int) (value * scale + 0.5f);
    }

    public static int px2dp(float value) {
        final float scale = CApplication.getInstance().getResources().getDisplayMetrics().density;
        return (int) (value / scale + 0.5f);
    }

}
